package com.fadadianqi.mall.admin.controller;

import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.commons.PrimaryKeyCreator;
import com.fadadianqi.mall.model.Nav;
import com.fadadianqi.mall.service.NavService;
import com.yeqiangwei.commons.util.ParamUtils;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller("admin_controller")
public class NavController {


    /**
     * 商城的后台管理地址以 /mall/adm 开始
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = {"/mall/adm/nav"}, method = RequestMethod.GET)
    public String showNav(HttpServletRequest request, ModelMap modelMap) {
        //modelMap.put("navs", navService.showTreeList());
        return "/mall/admin/nav";
    }

    /**
     * modified by aroot
     * 两个相同的地址spring是不能启动的
     * ajax页面固定目录前缀后要加ajax，这样将来利于用filter统一控制ajax的错误提示
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = {"/mall/adm/ajax/nav/items"}, method = RequestMethod.GET)
    public String refresh(HttpServletRequest request, ModelMap modelMap) {
        modelMap.put("navs", navService.showTreeList());
        return "/mall/admin/ajaxNavItems";
    }


    /**
     * 添加子菜单的ajax弹出框
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/mall/adm/ajax/nav/form", method = RequestMethod.GET)
    public String ajaxShowForm(HttpServletRequest request, ModelMap modelMap) {
        String id = ParamUtils.getString(request, "id", null);
        if (ValidatorHelper.isNotEmpty(id)) {
            // 主键不为空则表示动作为修改菜单
            Nav nav = navService.getById(id);
            modelMap.put("nav", nav);
        } else {
            // 主键为空表示新增菜单
            String rootId = null;
            String parentId = ParamUtils.getString(request, "parentId", null);
            Nav parentNav = navService.getById(parentId);
            if (null != parentNav) {
                rootId = parentNav.getRootId();
            }
            modelMap.put("parentNav", parentNav);
        }
        modelMap.put("navAll", navService.findAll());
        return "/mall/admin/ajaxNavForm";
    }

    private Nav create(HttpServletRequest request) {
        Nav nav = new Nav();
        nav.setId(PrimaryKeyCreator.create());
        nav.setIsHidden("1".equalsIgnoreCase(ParamUtils.getString(request, "isHidden", "0")));
        nav.setName(ParamUtils.getString(request, "name", null));
        String parentId = ParamUtils.getString(request, "parentId", null);
        nav.setParentId(parentId);
        if (parentId == null) {
            nav.setRootId(nav.getId());
            List<Nav> rootNavs = navService.findRootItems();
            nav.setOrderby(rootNavs.size());
        } else {
            nav.setOrderby(0);
            Nav fatherNav = navService.getById(parentId);
            if (fatherNav != null) {
                if (fatherNav.getLayer() == 0) {
                    nav.setRootId(fatherNav.getId());
                } else {
                    nav.setRootId(fatherNav.getRootId());
                }
                nav.setLayer(fatherNav.getLayer() + 1);
                List<Nav> navList = navService.findChildrenByParent(fatherNav);
                int index = 1;
                for (Nav otherNav : navList) {
                    otherNav.setOrderby(index);
                    navService.update(otherNav);
                    index ++;
                }
            }
        }
        String prefixUri = ParamUtils.getString(request, "prefixURI", null);
        nav.setPrefixURI(prefixUri);
        nav.setSuffixURI(ParamUtils.getString(request, "suffixURI", null));
        navService.save(nav);
        return nav;
    }

    private Nav update(HttpServletRequest request) {
        String id = ParamUtils.getString(request, "id", null);
        Nav nav = navService.findById(id);
        nav.setIsHidden("1".equals(ParamUtils.getString(request, "isHidden", "0")));
        String name = ParamUtils.getString(request, "name", null);
        nav.setName(name);
        String prefixUri = ParamUtils.getString(request, "prefixURI", null);
        nav.setSuffixURI(ParamUtils.getString(request, "suffixURI", null));
        nav.setPrefixURI(prefixUri);
        navService.update(nav);
        return nav;
    }

    @RequestMapping(value = "/mall/adm/ajax/nav/save", method = RequestMethod.POST)
    public ResponseEntity<String> ajaxSave(HttpServletRequest request) {
        String id = ParamUtils.getString(request, "id", null);
        Nav nav;
        if (ValidatorHelper.isEmpty(id)) {
            nav = create(request);
        } else {
            nav = update(request);
        }
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = new AjaxResult(nav, true, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    /**
     * 将导航向上移动，如果同层上面有导航则同层移动，如果已经是同层顶级导航则将这个导航移动到上一个层级的最后一个。
     * 这是一个从页面看相对智能的通过改变layer和order来实现导航排序的动作
     * doDown方法是此方法反向操作的一个实现
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/mall/adm/ajax/nav/up")
    public ResponseEntity<String> ajaxDoUp(HttpServletRequest request, ModelMap modelMap) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        String id = ParamUtils.getString(request, "id", null);
        Nav nav = navService.getById(id);
        try {
            navService.moveUp(nav);
        } catch (Exception e) {
            e.printStackTrace();
            // TODO someting
        }
        AjaxResult rs = new AjaxResult(null, Boolean.TRUE, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "/mall/adm/ajax/nav/down")
    public ResponseEntity<String> ajaxDoDown(HttpServletRequest request, ModelMap modelMap) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        String id = ParamUtils.getString(request, "id", null);
        Nav nav = navService.getById(id);
        try {
            navService.moveDown(nav);
        } catch (Exception e) {
            e.printStackTrace();
            // TODO something
        }
        AjaxResult rs = new AjaxResult(null, Boolean.TRUE, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @Autowired
    private NavService navService;

    @Autowired
    private MessageSource ms;
}
